#include <string>
#include <thread>

#include "scope_lock.h"

ScopeLockMgr::ScopeLockMgr(int hash_power) : hash_power_(hash_power) {
  hash_mask_ = (1U << hash_power) - 1;
  for (unsigned i = 0; i < Size(); i++) {
    mutex_pool_.emplace_back(new std::mutex());
  }
}

ScopeLockMgr::~ScopeLockMgr() {
  
}

unsigned ScopeLockMgr::hash(const rocksdb::Slice &key) {
  return static_cast<unsigned>(std::hash<std::string>{}(key.ToString()) &
                               hash_mask_);
}

unsigned ScopeLockMgr::Size() { return (1U << hash_power_); }

void ScopeLockMgr::Lock(const rocksdb::Slice &key) {
  mutex_pool_[hash(key)]->lock();
}

void ScopeLockMgr::UnLock(const rocksdb::Slice &key) {
  mutex_pool_[hash(key)]->unlock();
}
